//引入axios
import axios from 'axios'
import qs from 'qs';
import {Toast,Indicator} from 'mint-ui';
import store from './store'
import storage from './localstorage'
import config from './config'
import serve from './serve'
import judgeURL from './judgeURL'
//import * as types from './types'
let cancel, promiseArr = {}
const CancelToken = axios.CancelToken;
axios.defaults.baseURL = config.url
// //设置默认请求头
axios.defaults.headers = {
    //"Content-Type": "application/json",
    "content-type": "application/x-www-form-urlencoded",
}
axios.defaults.timeout = 10000
//请求拦截器
axios.interceptors.request.use(config => {
    // 设置默认token
    if (store.state.token) {
        //config.headers.Authorization = `token ${store.state.token}`
    }
    //发起请求时，取消掉当前正在进行的相同请求
    if (promiseArr[config.url]) {
        promiseArr[config.url]('操作取消')
        promiseArr[config.url] = cancel
    } else {
        promiseArr[config.url] = cancel
    }
    return config
}, error => {
    return Promise.reject(error)
})
//响应拦截器即异常处理
axios.interceptors.response.use(response => {
    return response
}, err => {
    if (err && err.response) {
        switch (err.response.status) {
            case 400:
                err.message = '错误请求'
                break;
            case 401:
                err.message = '未授权，请重新登录'
                /*// 401 清除token信息并跳转到登录页面
                 store.commit(types.LOGOUT)
                 // 只有在当前路由不是登录页面才跳转
                 router.currentRoute.path !== 'my-login' &&
                 router.replace({
                 path: 'my-login',
                 query: { redirect: router.currentRoute.path },
                 })*/
                break;
            case 403:
                err.message = '拒绝访问'
                break;
            case 404:
                err.message = '请求错误,未找到该资源'
                break;
            case 405:
                err.message = '请求方法未允许'
                break;
            case 408:
                err.message = '请求超时'
                break;
            case 500:
                err.message = '服务器端出错'
                break;
            case 501:
                err.message = '网络未实现'
                break;
            case 502:
                err.message = '网络错误'
                break;
            case 503:
                err.message = '服务不可用'
                break;
            case 504:
                err.message = '网络超时'
                break;
            case 505:
                err.message = 'http版本不支持该请求'
                break;
            default:
                err.message = `连接错误${err.response.status}`
        }
        Toast({message: err.message, duration: 2000});
        Promise.resolve(err.response)
    } else {
        err.message = "连接到服务器失败"
        return Promise.reject(err)
    }
    // Toast({message: err.message, duration: 2000});
    //return Promise.resolve(err.response)
})
/*if(judgeURL.getUrl('partner_id')){ //获取URL飞拉参数
    window.localStorage.partner_id = judgeURL.getUrl('partner_id')||null;
    console.log("http1111")
}*/

export default {
    //get请求
    get(url, params,loader) {
        var params = params || {};
        var loader = loader || false;
        if (storage.get('userinfo')) {
            var member_id = storage.get('userinfo').member_id || 0;
        }
        if (storage.get('openid')) {
            var openid = storage.get('openid') || 0;
        }
        if (storage.get('unionid')) {
            var unionid = storage.get('unionid') || 0;
        }

        if (storage.get('uid')) {
            var uid = storage.get('uid') || '';
        }
        if (storage.get('partner_id')) {
         var partner_id = storage.get('partner_id') || judgeURL.getUrl('partner_id');
         }
        //params.partner_id=partner_id
        params.token = storage.get('token') || '';
        params.member_id = member_id;
        params.openid = openid;
        params.unionid = unionid;
        params.uid = uid;
        params.partner_id=partner_id;

        return new Promise((resolve, reject) => {
            if(loader){
                Indicator.open({spinnerType: 'fading-circle'});
            }
            axios({
                method: 'get',
                url,
                params: params,
                cancelToken: new CancelToken(c => {
                    cancel = c
                })
            }).then(res => {
                    if(loader){
                        Indicator.close();
                    }
                    if (res.data.code == 0 || res.data.code == 200) {
                        resolve(res.data)
                    } else {
                        Toast({message: res.data.msg});

                    }
                })
                .catch(err => {
                    if(loader){
                        Indicator.close();
                    }
                    console.log(err);
                })
        })
    },
    //post请求
    post(url, params,loader) {
        var params = params || {};
        var loader = loader || false;
        var member_id = params.member_id;
        if (storage.get('userinfo')) {
            member_id = storage.get('userinfo').member_id || 0;
        }
        if (storage.get('openid')) {
            var openid = storage.get('openid') || 0;
        }
        if (storage.get('unionid')) {
            var unionid = storage.get('unionid') || 0;
        }
        if (storage.get('uid')) {
            var uid = storage.get('uid') || '';
        }
        if (storage.get('partner_id')) {
            var partner_id = storage.get('partner_id') || null;
        }

        params.token = !!storage.get('token') ? storage.get('token') : params.token;
        //params.token='e2ad278463c90d3472e77ee700b56aed';
        //params.member_id=143;
        params.member_id = member_id;
        params.openid = openid;
        params.unionid = unionid;
        params.uid = uid;
        params.partner_id=partner_id
        return new Promise((resolve, reject) => {
            if(loader){
                Indicator.open({spinnerType: 'fading-circle'});
            }
            axios({
                method: 'post',
                url,
                data: qs.stringify(params),
                cancelToken: new CancelToken(c => {
                    cancel = c
                })
            }).then(res => {
                    if(loader){
                        Indicator.close();
                    }
                    //console.log(res)
                    if (res.data.code == 0 || res.data.code == 200) {
                        resolve(res.data)
                    } else if(res.data.code == 401){
                        Toast({message: res.data.msg,duration: 5000,});
                    }else if(res.data.code==101){
                        Toast({message: res.data.msg,duration: 1000,});
                        Indicator.close();
                    }else {
                        Toast({message: res.data.msg,duration: 1000,});
                        Indicator.close();
                    }

                })
                .catch(err => {
                    if(loader){
                        Indicator.close();
                    }
                    console.log(err);
                })
        })
    },
    //post请求 未处理统一错误code
    postAll(url, params,loader) {
        var params = params || {};
        var loader = loader || false;
        if (storage.get('userinfo')) {
            var member_id = storage.get('userinfo').member_id || 0;
        }
        if (storage.get('openid')) {
            var openid = storage.get('openid') || 0;
        }
        if (storage.get('unionid')) {
            var unionid = storage.get('unionid') || 0;
        }
        if (storage.get('uid')) {
            var uid = storage.get('uid') || '';
        }
        if (storage.get('partner_id')) {
            var partner_id = storage.get('partner_id') || null;
        }
        params.token = storage.get('token') || '';
        params.member_id = member_id;
        params.openid = openid;
        params.unionid = unionid;
        params.uid = uid;
        params.partner_id=partner_id
        return new Promise((resolve, reject) => {
            if(loader){
                Indicator.open({spinnerType: 'fading-circle'});
            }
            axios({
                method: 'post',
                url,
                data: qs.stringify(params),
                cancelToken: new CancelToken(c => {
                    cancel = c
                })
            }).then(res => {
                    if(loader){
                        Indicator.close();
                    }
                    resolve(res)
                })
                .catch(err =>{
                    if(loader){
                        Indicator.close();
                    }
                    console.log(err);
                })
        })
    }
}